package pl.pawluk.inz.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import pl.pawluk.inz.dao.CourseMapper;
import pl.pawluk.inz.dao.ICourseService;
import pl.pawluk.inz.dao.UsersCoursesMapper;
import pl.pawluk.inz.dto.CourseDTO;
import pl.pawluk.inz.entities.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: mandp
 * Date: 18.04.13
 * Time: 20:43
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CourseService extends AbstractService<CourseDTO, Course> implements ICourseService {

    @Autowired
    private UsersCoursesMapper usersCoursesMapper;
    @Autowired
    private CourseMapper courseMapper;


    CourseService() {
        super(CourseDTO.class, Course.class);
    }

    @Override
    public List<CourseDTO> getAll() {
        List<CourseDTO> res = new ArrayList<CourseDTO>();
        convertToDTO(courseMapper.selectByExample(new CourseCriteria()), res);
        return res;
    }

    @Override
    public List<CourseDTO> getByUser(Long userId) {
        List<CourseDTO> res = new ArrayList<CourseDTO>();
        CourseCriteria crit = new CourseCriteria();
        UsersCoursesCriteria usersCoursesCriteria = new UsersCoursesCriteria();
        usersCoursesCriteria.createCriteria().andUserIdEqualTo(userId);
        List<UsersCoursesKey> joined = usersCoursesMapper.selectByExample(usersCoursesCriteria);
        if (joined != null && joined.size() > 0) {
            List<Long> courses = new ArrayList<Long>(joined.size());
            for (Iterator<UsersCoursesKey> ucIter = joined.iterator(); ucIter.hasNext(); ) {
                courses.add(ucIter.next().getCourseId());
            }
            crit.createCriteria().andIdIn(courses);
            convertToDTO(courseMapper.selectByExample(crit), res);
        }
        return res;
    }

    @Override
    public void create(CourseDTO course) {
        courseMapper.insertSelective(convertToENT(course));
    }

    @Override
    public void update(CourseDTO course) {
        courseMapper.updateByPrimaryKeySelective(convertToENT(course));
    }

    @Override
    public void delete(CourseDTO course) {
        courseMapper.deleteByPrimaryKey(course.getId());
    }
}
